﻿using Microsoft.AspNetCore.Mvc;
using STF.Blog.Common;
using STF.Blog.IService;
using STF.Blog.WebApp.Areas.ForumManage.Models.Reoly;
using X.PagedList;

namespace STF.Blog.WebApp.Areas.ForumManage.Controllers
{
    [Area("ForumManage")]
    public class ReplyController : Controller
    {
        private IReplyService _ireplySvc;
        private ICommentService _comSvc;
        private IUsersService _usersSvc;
        public ReplyController(IReplyService ireplySvc, ICommentService comSvc, IUsersService usersSvc)
        {
            _ireplySvc = ireplySvc;
            _comSvc = comSvc;
            _usersSvc = usersSvc;
        }

        [HttpGet]
        public async Task<IActionResult> Index(string search, int page = 1)
        {
            search = string.IsNullOrEmpty(search) ? "" : search;
            var data = await _ireplySvc.GetByNameAsync(search);
            var dataList = new List<ReplyListViewModel>();

            foreach (var item in data) 
            {
                var model = new ReplyListViewModel
                {
                    Id = item.Id,
                    Content = item.Content,
                    LikeSum = item.LikeSum,
                    UsersTitle = await GetUsersTitle(item.Uid),
                    CommentTitle = await GetCommentTitle(item.Pid),
                    ParentTitle = await GetParentTitle(item.ParentId),
                    UpdateTime = item.UpdateTime
                };
                dataList.Add(model);
            }

            ViewBag.Search = search;
            var pages = await dataList.ToPagedListAsync(page,PageConfig.PageSize);
            return View(pages);
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id) 
        {
            if (ModelState.IsValid) 
            {
                await _ireplySvc.PutTrashAsync(id);
                return Redirect("~/ForumManage/Reply/Index");
            }
            return View();
        }

        private async Task<string> GetUsersTitle(int id) 
        {
            var data = await _usersSvc.GetByIdAsync(id);
            return data == null ? "" :data.NickName;
        }

        private async Task<string> GetCommentTitle(int id) 
        {
            var data = await _comSvc.GetByIdAsync(id);
            return data == null ? "" : data.Content;
        }

        private async Task<string> GetParentTitle(int parentId) 
        {
            if (parentId == 0)
                return "无";
            var data = await _ireplySvc.GetByIdAsync(parentId);
            return data.Content;
        }

    }
}
